<template>
  <div class="main">
    <div class="options">
      <div class="item">
        <el-button title="主页" class="el-button item home" slot="reference" v-on:click="jumpToHome">
          <i class="el-icon-house unhover"></i>
          <i class="el-icon-s-home hover"></i>
        </el-button>
      </div>
      <div title="用户" class="item user">
        <el-popover>
          <div class="item">
            <el-tag class="username" type="plain" style="width: 100%;text-align: center">{{user.username}}</el-tag>
          </div>
          <div class="item">
            <el-button size="medium" type="text" icon="el-icon-switch-button" v-on:click="logout">注销登录</el-button>
          </div>
          <div class="item">
            <el-button size="medium" type="text" icon="el-icon-user" v-on:click="switchUser">切换账号</el-button>
          </div>
          <el-button class="el-button item home" slot="reference">
            <i class="el-icon-user unhover"></i>
            <i class="el-icon-user-solid hover"></i>
          </el-button>
        </el-popover>
      </div>
    </div>
    <div class="container">
      <p class="title">管理你的知识图谱数据库</p>
      <div id="download">
        <div class="list">
          <el-select v-model="radio" placeholder="请选择数据库">
            <el-option
                v-for="(item, index) in dataStores"
                :key="index"
                :label="item"
                :value="index"
            ></el-option>
          </el-select>
        </div>

        <el-button class="btn" type="primary" @click="openUploadWin()">上传数据</el-button>
        <el-button class="btn" type="primary" @click="loadData()">加载数据</el-button>
        <el-button class="btn" type="primary" @click="openDel()">删除数据</el-button>
        <el-button class="btn" type="primary" @click="downloadTemplate()">下载模板</el-button>

        <el-dialog title="上传数据" :visible.sync="dialogUploadVisible" width="30%">
          <div class="file-item" v-for="item of uploadFiles" v-bind:key="item.key">
            <input class="file" type="file" @change="getFile($event, item)"/>
            <el-input
                v-model="item.kgName"
                size="small"
                placeholder="请输入数据库名称"
                style="width: 40%; margin-right: 30px"
            ></el-input>
          </div>
          <div>
            <i class="add-btn el-icon-circle-plus-outline" @click="addFile()"></i>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="uploadDisable" @click="uploadSend()">确 定</el-button>
            <el-button @click="closeUpload()">取 消</el-button>
          </span>
        </el-dialog>

        <el-dialog
            title="删除数据库"
            :visible.sync="dialogDelVisible"
            width="30%"
        >
          <p>您确实要删除这个数据仓库吗？</p>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="delDisable" @click="del()">确 定</el-button>
            <el-button @click="dialogDelVisible = false">取 消</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {getListAPI, uploadFileAPI, loadDataAPI, deleteKgAPI} from "@/api/kgbuilder/kgbuilder";
import {mapGetters} from "vuex";
import global from "@/global";
import { logoutAPI } from "@/api/identify/identify";
export default {
  name: "kgbuilderold",
  data() {
    return {
      user: {},
      kgName: "",
      dataStores: [],
      kgIdList: [],
      dialogCreateVisible: false,
      dialogDelVisible: false,
      dialogUploadVisible: false,
      uploadDisable: false,
      delDisable: false,
      input: "",
      radio: "",
      uploadFiles: [],
      selectDataStore: "",
    };
  },

  created() {

    this.user = global.getUser();

  },

  mounted() {
    //get user id first
    this.getList();
  },

  computed: {
    ...mapGetters(['kgNameGlobal', 'kgInfo']) // 动态计算属性，相当于this.$store.getters.*
  },

  methods: {
    logout(){
      logoutAPI(()=>{
        this.$message.success("操作成功");
      },(errorMessage)=>{
        this.$message.error("操作失败：" + errorMessage);
      },()=>{
        this.$router.push({path:"/"});
        global.clearAll();
      });
    },
    switchUser(){
      logoutAPI(()=>{
        this.$message.success("操作成功");
      },(errorMessage)=>{
        this.$message.error("操作失败：" + errorMessage);
      },()=>{
        this.$router.push({path:"/identify"});
        global.clearAll();
      });
    },
    jumpToHome(){
      this.$router.push({ path:"/" });
    },
    getList() {
      this.dataStores = [];
      this.kgIdList = [];
      let _this = this;
      // 修改为get请求 用户登陆后所有请求不必携带其id
      // let formData = new FormData();
      // formData.append("userid", this.userId);
      getListAPI(
          function (data) {
            console.log('get list succeeded:', data);
            for (let i = 0; i < data.length; i++) {
              _this.dataStores.push(data[i][0]);
              _this.kgIdList.push(data[i][1]);
            }
          },
          function (error) {
            _this.$message.error("获取数据库列表失败：" + error);
          }
      );
    },

    openUploadWin() {
      this.uploadFiles = [];
      this.uploadFiles.push({kgName: "", file: ""});
      this.dialogUploadVisible = true;
    },

    addFile() {
      this.uploadFiles.push({kgName: "", file: ""});
    },

    getFile(event, item) {
      item.file = event.target.files[0];
    },

    uploadSend() {
      let toBeUploaded = this.getValidUploads();
      if (toBeUploaded === 0) {
        return;
      }

      this.uploadDisable = true;
      console.log('number of files:', toBeUploaded);

      let result = [];
      for (let i = 0; i < this.uploadFiles.length; i++) {
        if (this.uploadFiles[i].file !== "") {
          this.send(i,
              function () {
                result.push(true);
              },
              function () {
                result.push(false);
              });
        }
        if (i === this.uploadFiles.length - 1) {
          setTimeout(() => {
            this.verify(result, toBeUploaded);
          }, i * 600);
        }
      }
    },

    getValidUploads() {
      let toBeUploaded = 0;
      for (let i = 0; i < this.uploadFiles.length; i++) {
        if (this.uploadFiles[i].file === "") {
          if (this.uploadFiles[i].kgName !== "") {
            this.$message.error("请选择文件");
            return 0;
          }
          continue;
        }
        if (this.uploadFiles[i].kgName === "") {
          this.$message.error("数据库名称不能为空");
          return 0;
        }
        if (!this.allDiff(i)) {
          return 0;
        }
        toBeUploaded++;
      }
      if (toBeUploaded === 0) {
        this.$message.error("请选择文件");
      }
      return toBeUploaded;
    },

    allDiff(i) {
      for (let j = 0; j < this.uploadFiles.length; j++) {
        if (j !== i) {
          if (this.uploadFiles[j].kgName === this.uploadFiles[i].kgName) {
            this.$message.error("数据库名称不能相同");
            return false;
          }
        }
      }
      for (let j = 0; j < this.dataStores.length; j++) {
        if (this.dataStores[j] === this.uploadFiles[i].kgName) {
          this.$message.error("存在相同数据库名称，请换名称或者删除原数据库");
          return false;
        }
      }
      return true;
    },

    send(i, success, failed) {
      let loadingMessage = this.$message.loading("文件上传中...");

      let _this = this;
      let formData = new FormData();
      formData.append("file", this.uploadFiles[i].file);
      formData.append("kgName", this.uploadFiles[i].kgName);
      // formData.append("userid", this.userId);

      setTimeout(() => {
        uploadFileAPI(
            formData,
            function () {
              console.log("upload succeeded:", i);
              success();
            },
            function (error) {
              console.log(error.message);
              _this.$message.error("上传文件失败:" + error.message);
              _this.uploadFiles = [];
              _this.dialogUploadVisible = false;
              failed();
            },()=>{
              loadingMessage.close();
          }
        );
      }, i * 500);
    },

    verify(result, toBeUploaded) {
      let timer = setInterval(() => {
        if (result.length === toBeUploaded) {
          if (result.every((item) => item === true)) {
            this.$message.success("上传完成");
            this.dialogUploadVisible = false;
          } else {
            this.$message.error("上传失败");
          }
          this.uploadDisable = false;
          this.uploadFiles = [];
          this.getList();
          clearInterval(timer);
        }
      }, 500);
    },

    closeUpload() {
      this.dialogUploadVisible = false;
      this.uploadFiles = [];
    },

    loadData() {
      if (this.radio === "") {
        this.$message.error("请选择要加载的数据库");
        return;
      }

      let loadingMessage = this.$message.loading();

      let _this = this;
      loadDataAPI(
          this.kgIdList[this.radio],
          function (res) {
            console.log("load succeeded");
            //res即当前选中的图的所有信息，将此存入vuex中的kgInfo
            _this.$store.commit('modifyKgName', _this.dataStores[_this.radio]);
            _this.$store.commit('modifyKgInfo', res);
            _this.$router.push({
              name: 'KgEditor',
            })
            console.log(res);
          },
          function (error) {
            console.log(error);
            _this.$message.error("加载失败：" + error);
          },()=>{
           loadingMessage.close();
        });
    },

    openDel() {
      if (this.radio === "") {
        this.$message.error("请选择要删除的数据库");
        return;
      }
      this.dialogDelVisible = true;
    },

    del() {
      this.delDisable = true;
      let _this = this;
      // let formData = new FormData();
      // formData.append("kgId", this.kgIdList[this.radio]);
      deleteKgAPI(
          this.kgIdList[this.radio],
          function (res) {
            if (sessionStorage.getItem("store")) {
              sessionStorage.removeItem("store")
            }
            _this.$store.commit('modifyKgName', "");
            _this.$store.commit('modifyKgInfo', []);
            _this.getList();
            _this.dialogDelVisible = false;
            _this.radio = "";
            _this.delDisable = false;
            console.log(res);
            _this.$message.success("删除成功");
          },
          function (error) {
            _this.delDisable = false;
            _this.$message.error("删除失败：" + error);
            _this.dialogDelVisible = false;
          }
      );
    },

    downloadTemplate() {
      console.log('downloading');
      this.$message.success("开始下载……");
      window.location.href = `./template.csv`;
    }
  }
};
</script>

<style type="text/css" scoped>
@import "../../assets/kgbuilder.css";


</style>
